<template>
	<view class="infoPage">
		<loading style="z-index: 9999;" :showLoaded.sync="showLoaded"></loading>

		<memberMove v-if="memberListLength > 0" :newNumber='newNumber' @skipMemberGift='skipMemberGift'></memberMove>
		<onlineService></onlineService>
		<tabBar v-if="customTabbar === 1 && tabbarTimeout" :nowPages.sync="nowPages"></tabBar>
		<navBar v-if="isShowCustomNavBar" :navbarData.sync="navbarData"></navBar>
		<view class="paty-payment" :class="!isIpx ? 'paty-payment-ipx' : ''" @click="toOrder"
			v-if="!!partPaymentArr && partPaymentArr.some(item => item.status === 'BUYER_PART_PAYMENT')">
			<text>您有待付款的订单，请尽快完成付款</text>
			<image src='https://100000063-1252208446.file.myqcloud.com/images/arrowPay.png' mode="widthFix"></image>
		</view>
		<view
			:class="customTabbar && isIpx ? 'custom-tab-bottom-ipx' : customTabbar && !isIpx ? 'custom-tab-bottom' : ''">
			<view class="no_login" v-if="!userLogin">
				<image class="brandLogo" src="https://100000063-1252208446.file.myqcloud.com/images/MbrandLogo.png">
				</image>
				<view class="text">成为会员，享受更多专属福利</view>
				<view class="rights">
					<view class="right-item" v-for="(item, index) in rightsList" :key="index">
						<image class="right-icon" :src="item.icon"></image>
						<view class="right-name">{{ item.name }}</view>
					</view>
				</view>
				<view class="join_btn" @click="getUserProfile(true)">即刻入会</view>
				<!-- 列表 -->
				<NoLoginInfolist style="background-color: #fff;margin-top:80rpx"></NoLoginInfolist>
			</view>

			<view class="login_In" v-else>
				<view class="avatar-container"
					:class="(!!partPaymentArr && partPaymentArr.length > 0) ? 'avatar-top' : ''">
					<view class="welcome">欢迎回来！</view>
					<view class="avatar-content">
						<view class="avatar-l">
							<view class="avatar-url">
								<image class="avatar-image" mode="aspectFill" :src="userAvatarUrl"></image>
								<button class="edit-avatar" open-type="chooseAvatar"
									@chooseavatar="onChooseAvatar"></button>
							</view>
							<view class="avatar-name" v-if="!changeName">
								<text @click="updateName">{{ userNickName }}</text>
								<!-- <view class="updateNmae" @click="updateName"></view> -->
								<view class="updateNmae" @click="updateUserInfo"></view>
							</view>
							<view class="weui-input-container" v-else>
								<input :focus='inputFocus' type="nickname"
									style="font-size: 32rpx;font-family: NotoSansSC-Regular;" placeholder="请输入昵称"
									@blur='confirmName' maxlength='15' :disabled='disabledName' />
							</view>
						</view>


						<view class="member-time">
							<text>已加入会员{{ activatedAt }}天</text>
							<view class="member-rule" @click="toCMSmemberRule">
								<view class="text">会员规则</view>
								<image class="arrow" mode="widthFix"
									src="https://100000063-1252208446.file.myqcloud.com/images/Marrow.png"></image>
							</view>
						</view>
					</view>
				</view>
				<view class="member-card">
					<Carousel ref="childRef" :memberLevelInfo="memberLevelInfo" :memberTotalAmount="memberTotalAmount"
						:memberDetails="memberDetails" @dropdown-status-changed="handleDropdownStatusChanged"
						@memberExp="onMemberExp">
					</Carousel>
				</view>
				<view :class="dropisopen === null ? '' : (dropisopen ? 'animate-drop-down' : 'animate-drop-up')">
					<!-- 会员专区 -->
					<view style="padding:48rpx 0 80rpx 0; z-index: -99 !important;">
						<utools-parse :utoolsData="viptp" @triggerComponent="onTriggerComponent"></utools-parse>
					</view>
					<!-- 我的订单 -->
					<OrderList ref="orderList" :partPaymentArr="partPaymentArr"></OrderList>
					<!-- 列表 -->
					<view :style="showLoaded ? 'opacity:0' : 'opacity:1;margin-top:48rpx;'">
						<Infolist></Infolist>
					</view>
				</view>
			</view>
			<view style="width: 1px;height: 140rpx;" v-show='dropisopen'></view>
			<register-widget ref="registerWidgetRef" location="info" @registerSuccess='registerSuccess'
				@finish="onRegisterWidgetFinish" />
		</view>

		<block v-if="showMemberExp">
			<memberexp :memberDetails="memberDetails" :memberLevel="memberLevelIndex" @memberExp="onMemberExp" />
		</block>

	</view>
</template>

<script module="filterChecked" lang="wxs" src="../../utils/filter.wxs"></script>
<script>
	let observer = null;
	import Carousel from './components/Carousel.vue';
	import OrderList from './components/orderList.vue';
	import Infolist from './components/infolist.vue';
	import NoLoginInfolist from './components/nologininfolist.vue';
	import api from '@/api/api';
	import tip from '@/utils/tip';
	import util from '@/utils/util';
	import NavBar from '../../components/common/navbar';
	import TabBar from '../../components/common/tabbar';
	import Loading from '../../components/common/loading';
	import onlineService from '@/components/common/onlineService';
	import memberMove from './components/memberMove.vue';
	import memberExp from "./components/memberExp";
	import {
		SYSTEM_INFO,
		USER_INFO,
		USER_SPECICAL_INFO,
		CUSTOMER_INFO,
		MERCHANT_INFO,
		LOWER_WX_VERSION
	} from '@/utils/constant';
	import registerWidget from "@/components/register/register-widget.vue"
	export default {
		config: {
			navigationStyle: 'custom',
			navigationBarTitleText: ''
		},
		components: {
			navBar: NavBar,
			tabBar: TabBar,
			loading: Loading,
			registerWidget: registerWidget,
			onlineService: onlineService,
			memberMove: memberMove,
			carousel: Carousel,
			orderList: OrderList,
			infolist: Infolist,
			noLoginInfolist: NoLoginInfolist,
			memberexp: memberExp
		},

		data() {
			return {
				payalert: false,
				tabbarTimeout: false,
				dropisopen: null,
				customTabbar: -1,
				isIpx: false,
				isShowCustomNavBar: true,
				cmsWebview: 'cms/webview',
				cmsNotice: 'cms/memberNotice',
				nowPages: '',
				cartNum: 0,
				userAvatarUrl: 'https://100000063-1252208446.file.myqcloud.com/images/Davata.png',
				userNickName: '',
				isAuthUserInfo: false,
				navbarData: {
					showCapsule: 0, //是否显示左上角图标   1表示显示    0表示不显示
					isTopFixed: false,
					hideSearch: true, //隐藏搜索
					hideCenter: false
				},
				canIUse: false,
				appId: '',
				unionIdName: '',
				showMyOrder: false,
				showJoinMember: -1, // 加入会员  1：显示, 0 隐藏
				animationData: {},
				getCoupon: false,
				memberDetails: {},
				memberCoupons: [],
				memberTotalAmount: '0', //消费金额
				sourceCode: '', //入会渠道
				userLogin: false, // 用户是否登录
				openAppointment: this.$programSetting.openAppointment,

				background: '',
				hasReady: false,
				e: false,
				hasClick: [-1, -1],
				viptp: [],
				vipGrade: null,
				activatedAt: null,
				memberLevelInfo: [{ //会员积分信息
					memberLevel: 1,
					memberLevelName: "心享会员",
					// memberLevelId: 31,
					point: 0,
					upgradeLeft: 5000, //会员升级剩余金额
					levelKeepLeft: 0, //会员保级金额
					nextLevel: '畅享会员',
					nextLevelPoint: 0,
					percen: 0,
					memberLevelExpirationDate: null, // 会员到期时间
					bgc: 'https://100000063-1252208446.file.myqcloud.com/images/memberCard1.png',
					color: 'black',
					gradeColor: "rgba(162, 18, 21, 1)",
					icon3: "https://100000063-1252208446.file.myqcloud.com/images/Image(7).png",
					icon4: "https://100000063-1252208446.file.myqcloud.com/images/macallan-remvp/cart/Image (11).png",
					expText1: "rgba(0, 0, 0, 0.9)",
					expText2: "rgba(0, 0, 0, 0.54)",
				}, { //会员积分信息
					memberLevel: 2,
					memberLevelName: "畅享会员",
					// memberLevelId: 31,
					point: 0,
					upgradeLeft: 5000, //会员升级剩余金额
					levelKeepLeft: 0, //会员保级金额
					nextLevel: '尊享会员',
					nextLevelPoint: 5000,
					percen: 0,
					memberLevelExpirationDate: null, // 会员到期时间
					bgc: 'https://100000063-1252208446.file.myqcloud.com/images/memberCard2.png',
					color: '#fff',
					gradeColor: "rgba(255, 255, 255, 1)",
					icon3: "https://100000063-1252208446.file.myqcloud.com/images/Image(8).png",
					icon4: "https://100000063-1252208446.file.myqcloud.com/images/macallan-remvp/cart/Image (11).png",
					expText1: "rgba(255, 255, 255, 1)",
					expText2: "rgba(255, 255, 255, 0.78)",
				}, { //会员积分信息
					memberLevel: 3,
					memberLevelName: "尊享会员",
					// memberLevelId: 31,
					point: 0,
					upgradeLeft: 5000, //会员升级剩余金额
					levelKeepLeft: 0, //会员保级金额
					nextLevel: '未达成',
					nextLevelPoint: 10000,
					percen: 0,
					memberLevelExpirationDate: null, // 会员到期时间
					bgc: 'https://100000063-1252208446.file.myqcloud.com/images/MemberCard3.png',
					color: 'rgb(239,188,84)',
					gradeColor: "rgba(255, 200, 89, 1)",
					icon3: "https://100000063-1252208446.file.myqcloud.com/images/Image(8).png",
					icon4: "https://100000063-1252208446.file.myqcloud.com/images/macallan-remvp/cart/Image (10).png",
					expText1: "rgba(255, 255, 255, 1)",
					expText2: "rgba(255, 255, 255, 0.78)",
				}],
				memberListLength: 0,
				changeName: false,
				updateAvatarUrl: '',
				comInfo: true,
				inputFocus: false,
				showLoaded: true,
				disabledName: false,
				partPaymentArr: null,
				iconCutTime: 0,
				submitOrderId: '',
				enableLoad: true,
				newNumber: 0,
				rightsList: [{
					icon: 'https://100000063-1252208446.file.myqcloud.com/images/img1 (4).png',
					name: '专享购买'
				}, {
					icon: 'https://100000063-1252208446.file.myqcloud.com/images/img1 (1).png',
					name: '专享福利'
				}, {
					icon: 'https://100000063-1252208446.file.myqcloud.com/images/img1 (2).png',
					name: '品牌特邀'
				}, {
					icon: 'https://100000063-1252208446.file.myqcloud.com/images/img1 (3).png',
					name: '新品通知'
				}],
				showMemberExp: false,
				memberLevelIndex: 0
			};
		},
		onHide() {
			if (observer) {
				observer.disconnect()
			}
		},
		onUnload(options) {
			// 页面关闭后销毁实例
			if (observer) {
				observer.disconnect()
			}
			// this.interstitialAd.destroy()
		},
		async onLoad(option) {
			try {
				this.showLoaded = true;
				this.customTabbar = this.$programSetting.customTabbar ? 1 : 0
				await this.$onLaunched;

				const accountInfo = uni.getAccountInfoSync()
				let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
				if (option.sourcecode != undefined && option.sourcecode != null && option.sourcecode != '') {
					uni.setStorageSync('sourceCode', option.sourcecode);
				}

				this.sourceCode = uni.getStorageSync('sourceCode');
				const systemInfo = uni.getStorageSync(SYSTEM_INFO);
				this.isIpx = getApp().globalData.isIpx;
				this.cartNum = uni.getStorageSync('cartNum');
				let pages = getCurrentPages();
				let currPage = pages[pages.length - 1];
				this.nowPages = currPage.route;
				this.appId = accountInfo.miniProgram.appId
				// // 订单
				// this.getMyOrder();
				//会员专区
				// this.getStoreJson(option);
			} catch (e) {
				console.log("######## info-onLoad-error", e)
			}
		},
		async onShow() {
			try {
				await this.$onLaunched;
				let that = this
				that.$commonSensors.commonPageView('MemberPageView')
				setTimeout(() => {
					that.tabbarTimeout = true;
				}, 400)
				// if (uni.getStorageSync('buyerPartPayment')) {
				//   this.getMyOrder()
				// }
				// 订单
				this.getMyOrder();

				if (!!this.submitOrderId) {
					that.showLoaded = true
					this.getOrderInfo()
				}
				//判断用户是否入会
				let customerInfo = uni.getStorageSync(CUSTOMER_INFO) || '';
				if (!!customerInfo.jwt) {
					that.$commonFunction.commonLoginNew().then(function(res) {
						that.hasReady = true;
						customerInfo = res.data;
					}).catch(err => {
						that.showLoaded = false
					});
				} else {
					that.$commonFunction.commonLoginNew().then(function(res) {
						that.hasReady = true;
						customerInfo = res.data;
					}).catch(err => {
						that.showLoaded = false
						that.$set(that.navbarData, 'isTopFixed', true)
						that.$set(that.navbarData, 'hideCenter', true)
					});
				}

				//判断用户是否登录
				if (customerInfo) {
					that.getMemberDetail(customerInfo.jwt);
					this.userAvatarUrl = customerInfo.avatarUrl;
					this.userNickName = customerInfo.nickName;
				} else {
					this.userLogin = false;
					const userSpecialInfo = uni.getStorageSync('userSpecialInfo');
					let unionId = userSpecialInfo.unionId
					this.unionIdName = unionId.substring(unionId.length - 8)
				}
				getApp().cl_tracker.track('mini_program_view', {
					path: this.nowPages,
					pageName: '我的',
				})
			} catch (e) {
				console.log("######## info-onShow-error", e)
			}
		},
		//点击我的tabber埋点
		onTabItemTap(e) {
			let text = e.text
			let clTrackPrams = {
				'c_tab': "我的",
				'c_link_pagename': e.text,
				'c_link_path': e.pagePath
			}
			getApp().commonClTrack('c_ebmp_click_tabbar', clTrackPrams)
		},

		methods: {
			//埋点
			onTriggerComponent(data) {
			  try {
			    this.$commonUtoolsTrack.onTriggerComponent(data);
			  } catch (e) {}
			},
			/**
			 * 查询当前用户是否有ts活动
			 */
			async getTsActiveByUser() {
				try {
					let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
					let merchantInfo = uni.getStorageSync("merchantInfo");
					let memberDetails = uni.getStorageSync("memberDetails");
					if (!memberDetails || !customerInfo || !merchantInfo) return 0;
					const result = await api.getTsByUser({
						header: {
							jwt: customerInfo.jwt,
						},
						method: "GET",
						query: {
							store_id: merchantInfo.cloudMerchantStoreId,
							group_id: customerInfo.groupId,
							member_level_id: memberDetails.memberLevelId,
						},
					});
					if (result && result.code === 1000 && result.data && result.data.campaignTargetSaleId) {
						return result.data.campaignTargetSaleId;
					}
					return 0;
				} catch (e) {
					console.log("#####  getTsActiveByUser-error:", e);
					return 0;
				}
			},
			/**
			 * 获取商品高清大图
			 * @param {Object} merchantInfo
			 * @param {Object} itemId
			 */
			async getDetailsById(merchantInfo, itemId) {
				return new Promise(async (resolve, reject) => {
					const _res = await api.goodsDetail({
							query: {
								merchant_id: merchantInfo.cloudMerchantId,
								store_id: merchantInfo.cloudMerchantStoreId
							}
						},
						itemId
					);
					let _img = "";
					if (_res && _res.code == 1000 && _res.data && _res.data.resources && _res.data
						.resources.length) {
						const _obj = _res.data.resources.find((item) => item.kind == "hdlp");
						if (_obj && _obj.kind == "hdlp" && _obj.type == "image" && _obj.url) _img = _obj
							.url;
					}
					resolve(_img);
				})
			},
			gotowx() {
				uni.navigateTo({
					url: '/pages/public-account/public-account',
				})
			},
			handleDropdownStatusChanged(isOpen) {
				// 在这里处理 isDropDownOpen 的值
				this.dropisopen = isOpen
			},
			/**
			 * 获取utools数据
			 * @param {Object} option url参数
			 */
			async getStoreJson(option) {
				try {

					let json;
					//  特邀活动
				 let _tA = await this.getActivityList()
						//  获取用户是否有ts活动信息
				const _tsId = await this.getTsActiveByUser();

				json = await api.getUtoolsJson({
					type: "vipAll"
				});
				if (json.code === 200 && json.data) {
					let _uData = JSON.parse(json.data);
					_uData.children = _uData?.children ? _uData?.children.map(item=>{
							if(item.boxType=='heightAuto') {
								item.children = item.children.filter(item=> {
									let isShow =false
									 if(_tA.length)  {
										isShow = _tA.find(ite=> ite.name == item.name1 && item.boxType=='invitedEvent')
										if (isShow && isShow.activityType == 'Gift') {
											// 会员礼品
											item.children =  item.children ? item.children.map(itemx=>{
												if(itemx.type == "hotSpace") {
													itemx.href = itemx.href+ `?id=${isShow.activityId}&name=${isShow.name}`
												}
												return itemx
											}):[]
											   // url: '/pages/memberGift/giftDetail?id=' + item.activityId
										} else if (isShow&&isShow.activityType == 'Exclusive_Adviser') {
											// 专属顾问
										    // url: '/pages/memberGift/consult?id=' + item.activityId + '&name=' + item.name
										}
									 }
									return item.boxType == "normal" || (_tsId&& item.label1==_tsId && item.boxType=="TS") || isShow
								})
							}
							return item
					}) :[]
						this.viptp = _uData
						return null
					//  筛选活动和默认活动都不存在  直接不展示会员专区模块
				}

				} catch (e) {
					console.log("##### getStoreJson-error:", e)
				}
			},
			async getSpecialInviteInfo(item) {
			  let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
			  const res = await api.getSpecialInviteInfo({
			    header: {
			      jwt: customerInfo.jwt
			    }
			  }, item.activityId);
			  conso
			  // if (res.code === 1000) {
			  //   if (res.data.urlType == 1) {
			  //     uni.navigateTo({
			  //       url: '/pages/cms/page?identifier=' + res.data.cmsUrl.url + '&activityName=' + item.name
			  //     })
			  //   } else if (res.data.urlType == 2) {
			  //     uni.navigateToMiniProgram({
			  //       appId: res.data.cmsUrl.appId,
			  //       path: res.data.cmsUrl.url,
			  //       envVersion: 'release',
			  //     });
			  //   }
			  // }
			},
			onRegisterWidgetFinish(e) {
				if (e.componentName == 'message-modal') {
					uni.setStorageSync('firstEnter', true)
				}
			},
			async getOrderInfo() {
				let that = this
				let customerInfo = uni.getStorageSync(CUSTOMER_INFO)
				const json = await api.getOrderInfo({
						header: {
							jwt: customerInfo.jwt
						}
					},
					this.submitOrderId
				);
				if (json.code === 1000) {
					if (json.data.status == 'WAIT_SELLER_SEND_GOODS') {
						uni.redirectTo({
							url: '/pages/order/paySuccess?orderNo=' + this.submitOrderId
						});
						this.submitOrderId = ''
					} else {
						that.showLoaded = false
					}
				} else {
					that.showLoaded = false
				}
			},
			//付款
			payMoney: async function() {
				let that = this;
				const accountInfo = uni.getAccountInfoSync()
				let {
					orderId,
					orderCode,
					payType
				} = this.partPaymentArr[0]
				//获取item传参埋点
				let currentOrderInfo = this.partPaymentArr[0]
				let itemIdArr = []
				let itemArr = []
				currentOrderInfo.items.forEach(function(item, index) {
					itemIdArr.push(item.itemId)
					itemArr.push({
						itemId: item.itemId,
						itemName: item.itemName,
						price: item.price,
						qty: item.qty,
						remark: currentOrderInfo.buyerRemark,
						skuInfo: {
							itemCapacity: item.skuProperties[0].valueName,
						},
					})
				});
				this.submitOrderId = orderId
				let orderFlow = this.$programSetting.openAppointment;
				let objOrder = this.$commonFunction.isOrderType(currentOrderInfo, orderFlow);
				that.$commonFunction.payMoney(this.partPaymentArr[0], this, objOrder, '个人中心').then((res) => {
					tip.loaded();
					setTimeout(() => {
						uni.redirectTo({
							url: '/pages/order/paySuccess?orderNo=' + orderId
						});
					}, 1000);
				}).catch((err) => {})

			},
			toOrder() {
				this.payMoney()
			},
			getMyOrder: async function() {
				let that = this;
				let merchantInfo = uni.getStorageSync(MERCHANT_INFO);
				let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
				const parmas = {
					customer_id: customerInfo.customerId,
					merchant_id: merchantInfo.cloudMerchantId,
					store_id: merchantInfo.cloudMerchantStoreId,
					page_no: 1,
					page_size: 20,
					// status: 'BUYER_PART_PAYMENT'
				};
				let json = await api.getMyOrderList({
					header: {
						jwt: customerInfo.jwt
					},
					query: parmas
				});
				if (json.data.code === 1000 && !!json.data.data.content && json.data.data.content.length > 0) {
					let _partPaymentArr = json.data.data.content;
					let merchantInfo = uni.getStorageSync(MERCHANT_INFO);
					let promises = []; // 存储所有的promise
					const _statusArr = ['WAIT_SELLER_SEND_GOODS', 'WAIT_BUYER_PAY', 'BUYER_PART_PAYMENT',
						'WAIT_BUYER_CONFIRM_GOODS'
					];
					const _sa = ['WAIT_SELLER_SEND_GOODS', 'WAIT_BUYER_CONFIRM_GOODS'];
					_partPaymentArr = _partPaymentArr.filter(item => _statusArr.includes(item.status));
					for (let i = 0; i < _partPaymentArr.length; i++) {
						_partPaymentArr[i].textColor = _sa.includes(_partPaymentArr[i].status) ? '#75777A' : '#CB171A';
						_partPaymentArr[i].items = _partPaymentArr[i].items.sort((a, b) => b.divideOrderFee - a
							.divideOrderFee);
						for (let k = 0; k < _partPaymentArr[i].items.length; k++) {
							if (k < 2) {
								if (_partPaymentArr[i].items && _partPaymentArr[i].items.length > 0) {
									let _hdImg = await this.getDetailsById(merchantInfo, _partPaymentArr[i].items[0]
										.itemId);
									if (_hdImg) _partPaymentArr[i].items[0].skuImageUrl = _hdImg;
									if (_partPaymentArr[i].items.length > 1) {
										let _hdImg2 = await this.getDetailsById(merchantInfo, _partPaymentArr[i].items[
											1].itemId);
										if (_hdImg2) _partPaymentArr[i].items[1].skuImageUrl = _hdImg2;
									}
								}
							}
						}
					}
					// 过滤出指定状态的订单项
					this.partPaymentArr = _partPaymentArr;
					this.$refs.orderList?.setOrderLists(_partPaymentArr);
					this.getIconTime();
				} else {
					this.partPaymentArr = null
				}
			},
			getIconTime() {
				let orderInfo = this.partPaymentArr[0];
				if (!orderInfo) return this.partPaymentArr = [];

				let iconCutTime;
				let systemInfo = uni.getStorageSync(SYSTEM_INFO);
				let isIos = systemInfo.system.indexOf('iOS');
				let cancelTime = getApp().globalData.cancelTime * 60;
				let nowTime = new Date().getTime()

				if (!!orderInfo.planEndTime) {
					if (isIos == 0) {
						iconCutTime = (new Date(orderInfo.planEndTime.replace(/-/g, '/')).getTime() - nowTime)
					} else {
						iconCutTime = (new Date(orderInfo.planEndTime).getTime() - nowTime)
					}
				} else {
					if (!!orderInfo.approveTime) {
						if (isIos == 0) {
							iconCutTime = cancelTime - (nowTime - new Date(orderInfo.approveTime.replace(/-/g, '/'))
								.getTime())
						} else {
							iconCutTime = cancelTime - (nowTime - new Date(orderInfo.approveTime).getTime())
						}
					} else {
						if (isIos == 0) {
							iconCutTime = cancelTime - (nowTime - new Date(orderInfo.createTime.replace(/-/g, '/'))
								.getTime())
						} else {
							iconCutTime = cancelTime - (nowTime - new Date(orderInfo.createTime).getTime())
						}
					}
				}
				if (iconCutTime > 0) {
					setTimeout(() => {
						this.getMyOrder();
					}, iconCutTime);
				} else {
					this.partPaymentArr = [];
				}
			},
			updateName() {
				this.changeName = true
				this.inputFocus = true
				this.$commonSensors.commonPageClick('MemberPageClick', '编辑昵称')
			},
			updateUserInfo() {
				uni.navigateTo({
					url: '/pages/customer/registerSetting'
				})
			},
			confirmName(e) {
				let value = e.detail.value
				this.updateCustomerInfo(value)
			},
			onChooseAvatar: function(e) {
				let that = this
				that.updateAvatarUrl = e.detail.avatarUrl;
				that.$commonSensors.commonPageClick('MemberPageClick', '编辑头像')
				uni.uploadFile({
					url: api.uploadFiles2,
					// url: 'https://api.sandbox.cloud.efashionchina.com/cloud/basic-storage-tencent-cos/file?bucketName=100000000',
					filePath: that.updateAvatarUrl,
					name: 'file', // 固定 // 请求头一定要加，否则 iOS 图片上传会失败
					header: {
						'content-type': 'multipart/form-data'
					},
					success(res) {
						that.updateAvatarUrl = JSON.parse(res.data).data.url;
						that.updateCustomerInfo();
					},
					fail: function(err) {},
					complete(res) {}
				})
			},
			updateCustomerInfo: async function(name) {
				let that = this;
				let customerInfo = uni.getStorageSync(CUSTOMER_INFO)
				let jwt = uni.getStorageSync(CUSTOMER_INFO).jwt;
				let avatarUrl = that.updateAvatarUrl || that.userAvatarUrl;
				let nickName = name || customerInfo.nickName
				const json = await api.memberUpdate({
					method: 'PUT',
					header: {
						jwt: jwt
					},
					query: {
						avatarUrl: avatarUrl,
						nickName: nickName,
					}
				}, );
				if (json.code === 1000) {
					//刷新customer接口数据里的头像
					that.changeName = false
					that.userAvatarUrl = avatarUrl;
					that.userNickName = nickName;
					that.$commonFunction.commonLoginNew().then(function(res) {
						let customerNewInfo = uni.getStorageSync(CUSTOMER_INFO);
						that.updateAvatarUrl = ''
					}).catch((err) => {});
				}
			},
			// 任务中心
			async getTaskInfo() {
				let info = await getApp().getTaskInfo()
				if (info.contentList) {
					let list = info.contentList[0].content
					if (list.length > 0) {
						this.cmsWebview = 'cms/webview3'
					} else {
						this.cmsWebview = 'cms/webview'
					}
				} else {
					this.cmsWebview = 'cms/webview'
				}
			},
			// 会员礼遇
			// async getActivityList() {
			// 	let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
			// 	const res = await api.getActivityList({
			// 		header: {
			// 			jwt: customerInfo.jwt
			// 		}
			// 	});
		
			// 	if (res.code === 1000) {
			// 		this.memberListLength = res.data && res.data.length
			// 		let menuList = res.data
			// 		if (menuList && menuList.length > 0) {
			// 			let list = menuList.filter((item) => (
			// 				item.hasVisited == false
			// 			))
			// 			this.newNumber = list.length
			// 		} else {
			// 			this.newNumber = 0
			// 		}
			// 	}
			// 	this.showLoaded = false
			// },
			skipMemberGift() {
				let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
				let clTrackPrams = {
					'c_area': '我的礼遇',
					'c_link_pagename': '我的礼遇',
					'c_link_path': '/pages/memberGift/memberGiftList'
				}
				getApp().commonClTrack('c_ebmp_my_click', clTrackPrams)
				if (!customerInfo) {
					this.getUserProfile()
					return false
				}
				uni.navigateTo({
					url: '/pages/memberGift/memberGiftList'
				})
			},
			// 获取活动列表
			 async getActivityList() {
			   let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
			   const res = await api.getActivityList({
			     header: {
			       jwt: customerInfo.jwt
			     }
			   });
			   let menuList= [];
			   if (res.code === 1000) {
			     menuList = res.data || [];
			   }
          let nowTime = new Date().getTime()
          menuList =menuList.length? menuList.filter(item=>{
            let endT = util.formatTimeStamp(item.toDate)
            return endT>nowTime
          }):[]
			   return  menuList
			 },
			toCMSmemberRule() {
				this.$commonSensors.commonPageClick('MemberPageClick', '会员规则')
				uni.navigateTo({
					url: "/pages/customer/memberRules?tab=0"
				});
			},
			toSettings() {
				uni.navigateTo({
					url: '/pages/customer/settings'
				});
				//账号设置埋点
				let clTrackPrams = {
					'c_area': '账号设置',
					'c_link_pagename': '账号设置',
					'c_link_path': '/pages/customer/settings'
				}
				getApp().commonClTrack('c_ebmp_my_click', clTrackPrams)
			},
			toMemberGrowth() {
				this.$commonSensors.commonPageClick('MemberPageClick', '会员权益')
				uni.navigateTo({
					url: '/pages/customer/memberGrowth'
				})
			},
			registerSuccess() {
				this.$commonFunction.commonLoginNew().then((res) => {
					let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
					// 用户是否登录
					if (uni.getStorageSync(CUSTOMER_INFO)) {
						this.userLogin = true;
						if (!!customerInfo.avatarUrl) {
							this.userAvatarUrl = customerInfo.avatarUrl;
						}
						if (!!customerInfo.nickName) {
							this.userNickName = customerInfo.nickName;
						}
					} else {
						this.userLogin = false;
					}
					this.getMemberDetail(customerInfo.jwt)
					if (this.hasClick !== [-1, -1]) {
						this.tabMenuClick(this.hasClick[0], this.hasClick[0])
					}
				}).catch(() => {})
			},
			getUserProfile: async function(track) {
				if (track) {
					let clTrackPrams = {
						'c_area': '加入会员',
						'c_link_pagename': '',
						'c_link_path': ''
					}
					getApp().commonClTrack('c_ebmp_my_click', clTrackPrams)
					this.$commonSensors.registerButtonClick('我的')
				}
				this.$commonFunction.commonLoginNew().then(res => {
					if (res.code !== 1000) {
						this.$refs.registerWidgetRef.openJoinMemberModal()
					} else if (res.data && res.data.mobile) {
						//  非大陆手机号按照非会员对待,重新入会
						const phoneNumberReg = /^1\d{10}$/;
						if (!phoneNumberReg.test(res.data.mobile)) {
							this.$refs.registerWidgetRef.openJoinMemberModal()
						}
					}
				}).catch(err => {
					this.$refs.registerWidgetRef.openJoinMemberModal()
				})
			},
			/**
			 * 判断是否是会员
			 *
			 * @param jwt
			 * @return {Promise<void>}
			 */
			getMemberDetail: async function(jwt) {
				let that = this;
				let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
				const memberDetailsResult = await api.getMemberDetails({
					header: {
						jwt: customerInfo.jwt || jwt
					}
				});
				if (memberDetailsResult.code == 1000 && memberDetailsResult.data) {
					const phoneNumberReg = /^1\d{10}$/;
					if (!phoneNumberReg.test(memberDetailsResult.data.mobile)) {
						// 非大陆手机号按照非会员对待,重新入会
						uni.removeStorageSync('memberDetails');
						that.showJoinMember = 1;
						that.hasReady = true;
						that.showLoaded = false;
						that.userLogin = false;
						return;
					}
					that.userLogin = true;
					that.memberDetails = memberDetailsResult.data;
					this.$set(that.navbarData, 'isTopFixed', false)
					this.$set(that.navbarData, 'hideCenter', false)
					uni.setStorageSync('memberDetails', memberDetailsResult.data)
					const {
						gender,
						nickName,
						province,
						birthDay,
						mobile
					} = memberDetailsResult.data;

					if (!!gender && !!nickName && !!province && !!birthDay && !!mobile) {
						that.comInfo = false
					} else {
						that.comInfo = true
					}
					that.hasReady = true;
					if (that.memberDetails.isActive == 'Inactive') {
						that.showJoinMember = 1;
					} else {
						that.showJoinMember = 0;
						that.showGetCoupon = 0;
						this.vipGrade = that.memberDetails.memberLevel.levelName
						// this.vipGrade='畅享会员'
						await this.getStoreJson();
					}

					// 入会时间
					const providedDate = new Date(that.memberDetails.activatedAt);
					const currentDate = new Date();
					const diffTime = Math.abs(providedDate - currentDate);
					const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
					this.activatedAt = diffDays

					for (let i = 0; i < that.memberLevelInfo.length; i++) {
						if (that.memberDetails.memberLevel.levelName === that.memberLevelInfo[i].memberLevelName) {
							that.memberLevelInfo[i].point = that.memberDetails.c_exp_12M ? parseFloat(that
								.memberDetails.c_exp_12M) : 0;
						}

						that.memberLevelInfo[i].upgradeLeft = that.memberDetails[`upgradeLeft`] ? that.memberDetails[
							`upgradeLeft`] : 5000;

						that.memberLevelInfo[i].levelKeepLeft = that.memberDetails[`levelKeepLeft`] ? that
							.memberDetails[`levelKeepLeft`] : 0;

						if (that.memberLevelInfo[i].memberLevel === 3) {
							that.memberLevelInfo[i].startPoint = 10000;
						} else if (that.memberLevelInfo[i].memberLevel === 2) {
							that.memberLevelInfo[i].startPoint = 5000;
							that.memberLevelInfo[i].endPoint = 10000;
						} else {
							that.memberLevelInfo[i].startPoint = 0;
							that.memberLevelInfo[i].endPoint = 5000;
						}

						let num = 0;
						if (that.memberDetails.c_exp_12M != 0 && that.memberDetails.c_exp_12M != null) {
							if (that.memberLevelInfo[i].memberLevel === 3) {
								num = that.memberDetails.c_exp_12M >= that.memberLevelInfo[i].startPoint ? 100 : 0;
							} else {
								num = (that.memberDetails.c_exp_12M / that.memberLevelInfo[i].endPoint).toFixed(2) *
									100;
							}
						}
						that.memberLevelInfo[i].percen = num >= 100 ? 100 : num;
						that.memberLevelInfo[i].memberLevelExpirationDate = that.memberDetails[
							`memberLevelExpirationDate`];
					}

					if (this.$refs.childRef) {
						// 调用子组件的方法，将值传递过去
						this.$refs.childRef.getparent({
							exp_12M: that.memberDetails.c_exp_12M,
							lavelName: that.memberDetails.memberLevel.levelName
						});
					}

					if (that.showJoinMember === 0) {
						that.getTransactionAmounts(jwt);
					}

					this.$commonFunction.setInitTaskCenter().then(() => {
						this.getTaskInfo();
					}).catch(() => {})
					// that.getActivityList();
					this.showLoaded = false
				} else {
					that.showJoinMember = 1;
					that.hasReady = true;
				}
			},
			/**
			 * 计算用户消费金额
			 * Number.isInteger(3) // true
			 * Number.isInteger(3.1) // false
			 */
			getTransactionAmounts: async function(jwt) {
				let that = this;
				const transactionAmounts = await api.getTransactionAmounts({
					method: 'GET',
					header: {
						jwt: jwt
					},
					query: {
						period: 'LAST_365_DAYS'
					}
				});
				if (transactionAmounts.code == 1000) {
					let memberAmounts = transactionAmounts.data;
					if (Number(memberAmounts.orderAmount) >= 0 && Number(memberAmounts.refundAmount) >= 0) {
						let accumulated = memberAmounts.orderAmount - memberAmounts.refundAmount;
						if (Number.isInteger(accumulated)) {
							that.memberTotalAmount = accumulated;
							let amountFixed = accumulated.toFixed(2);
							let f_x = amountFixed.toString();
							let pos_decimal = f_x.split('.');
							let s_x = pos_decimal[1];
							if (s_x.length < 2) {
								s_x += '0';
							}
							that.memberTotalAmount = pos_decimal[0] + '.' + s_x;
						}
						if (accumulated <= 0) {
							that.memberTotalAmount = 0;
						}
					}
				}
			},
			//  开启/关闭我的经验值弹窗
			onMemberExp(e) {
				const index = this.memberLevelInfo.findIndex((item) => this.memberDetails.memberLevel.levelName === item
					.memberLevelName);
				this.memberLevelIndex = index != -1 ? index : 0;
				this.memberLevelIndex = this.memberLevelIndex + 1;
				this.showMemberExp = !this.showMemberExp;

				if (this.showMemberExp) this.$commonSensors.lithaTrack.popupClick({
					popup_type: "会员",
					popup_name: "会员经验值弹窗"
				});
			}
		}
	};
</script>

<style lang="less">
	.custom-tab-bottom-ipx {
		padding-bottom: 180rpx;
	}

	.no_login {
		display: flex;
		align-items: center;
		flex-direction: column;
		justify-content: center;
		background-color: #F2F2F2;

		.brandLogo {
			padding-top: 256rpx;
			width: 368rpx;
			height: 80rpx;
		}

		.text {
			font-family: "NotoSansSC-Regular";
			font-size: 32rpx;
			text-align: center;
			margin-top: 64rpx;
			color: rgba(0, 0, 0, 0.54);
		}

		.rights {
			padding: 80rpx 64rpx;
			display: flex;
			width: 100%;
			justify-content: space-between;

			.right-item {
				display: flex;
				align-items: center;
				flex-direction: column;
				width: 96rpx;

				.right-icon {
					width: 80rpx;
					height: 80rpx;
				}

				.right-name {
					padding-top: 16rpx;
					color: rgba(0, 0, 0, 0.54);
					font-size: 24rpx;
					font-family: "FrankNew-Medium";
				}
			}
		}

		.join_btn {
			color: #fff;
			width: 622rpx;
			height: 80rpx;
			display: flex;
			font-size: 28rpx;
			align-items: center;
			justify-content: center;
			font-family: "FrankNew-Medium";
			background-color: #CB171A;
			border-radius: 24px 8px 24px 24px;
		}
	}

	.login_In {
		.avatar-container {
			padding: 64rpx 60rpx 64rpx 48rpx;
			height: 320rpx;
			display: flex;
			justify-content: space-between;
			flex-direction: column;

			&.avatar-top {
				margin-top: 40rpx;
			}

			.welcome {
				color: #000;
				font-size: 48rpx;
				font-weight: 500;
				font-family: "NotoSansSC-Medium";
			}

			.avatar-content {
				position: relative;
				width: 100%;
				display: flex;
				align-items: center;
				justify-content: space-between;

				.avatar-l {
					display: flex;
					flex: 1;
					align-items: center;

					.avatar-url {
						width: 96rpx;
						height: 96rpx;
						position: relative;
						margin-right: 24rpx;
						flex-shrink: 0;

						.avatar-image {
							width: 100%;
							height: 100%;
							border-radius: 50%;
							margin-right: 24rpx;
						}

						.edit-avatar {
							position: absolute;
							top: 0;
							left: 0;
							right: 0;
							bottom: 0;
							background: none;
						}
					}

					.avatar-name {
						font-size: 32rpx;
						font-family: "NotoSansSC-Medium";
						position: relative;
						top: -20rpx;

						.updateNmae {
							position: absolute;
							right: -48rpx;
							bottom: 0rpx;
							width: 44rpx;
							height: 44rpx;
							background-image: url('https://100000063-1252208446.file.myqcloud.com/images/Medit.png');
							background-repeat: no-repeat;
							background-size: 100% 100%;
							text-align: left;
						}
					}

					.weui-input-container {
						width: 100%;
						overflow: hidden;
						margin-bottom: 20rpx;

						.weui-input {
							color: #fff;
							font-size: 32rpx;
							text-align: left;
							overflow: hidden;
							font-family: "NotoSansSC-Regular";
						}
					}
				}

				.member-time {
					display: flex;
					justify-content: space-between;
					position: absolute;
					left: 120rpx;
					top: 55rpx;
					width: 536rpx;
					height: 40rpx;
					font-family: FrankNew-Regular, NotoSansSC-Regular;
					font-style: normal;
					font-weight: 400;
					font-size: 24rpx;
					line-height: 40rpx;
					color: #757575;
				}

			}

			.member-rule {
				display: flex;
				align-items: center;
				justify-content: space-between;
				width: 120rpx;

				.text {
					font-size: 24rpx;
					font-family: "NotoSansSC-Regular";
					color: rgba(117, 117, 117, 1);
					padding-right: 12rpx;
					font-weight: 400;

				}

				.arrow {
					width: 12rpx;
				}
			}
		}

		.member-card {
			height: 384rpx;
			// margin: 0 28rpx 0;

			.card-container {
				height: 100%;
				width: 100%;

				background-size: 100% 100%;
				background-repeat: no-repeat;
				display: flex;
				flex-direction: column;
				justify-content: space-between;

			}

		}
	}

	.wx-swiper-dot {
		width: 42rpx !important;
		height: 4rpx !important;
		border-radius: 0 !important;
		margin-left: -16rpx !important;
	}

	.wx-swiper-dots {
		display: flex;
		justify-content: center;
		margin-left: 8rpx;

	}

	.swiper-dots-none {
		.wx-swiper-dots {
			display: none !important;

		}
	}

	page {
		width: 100%;
		background-color: #f7f5f4 !important;

		.infoPage {
			overflow: hidden;
			background-color: #fff;
		}
	}

	.member {
		text-decoration: underline;
		color: #fff;
	}

	.member-Level {
		color: #fff;
	}

	.info_block {
		// padding-bottom: 160rpx;

		.item {
			background: #fff;
			padding: 34rpx 28rpx;
			text-align: center;
			position: relative;

			.macallan-icon {
				height: 66rpx;
				font-size: 66rpx;
				margin-bottom: 16rpx;
				display: flex;
				align-items: center;
				justify-content: center;

				&.mcl-lujing {
					font-size: 56rpx;

				}
			}
		}

		.item_content {
			display: flex;
			align-items: center;
			justify-content: center;

			.text {
				color: #1a1a1a;
			}
		}

		.item_img {
			width: 42rpx;
			height: 42rpx;
		}

		.arrow {
			color: #cccccc;
			font-size: 32rpx;
		}

		.tip {
			color: #999;
			font-size: 24rpx;
			margin-top: 20rpx;
			margin-left: 60rpx;
		}
	}

	.info_block .item .item_img {
		display: none;
	}

	.info_block .myOrder {
		padding-left: 40rpx;

		.weui-cells .item {
			border: none;
		}

	}

	.item-icon {
		width: 32rpx;
		position: absolute;
		top: 0;
		right: 0;

		image {
			width: 100%;
			height: 100%;
		}
	}

	.fade_in {
		padding-left: 40rpx;
		opacity: 0;
		animation: mymove 1s 1;
		animation-fill-mode: forwards;
	}

	@keyframes mymove {
		from {
			height: 0;
		}

		to {
			height: 92rpx;
		}
	}

	.fade_out {
		padding-left: 40rpx;
		opacity: 0;
		animation: mymoveout 3s 1;
		animation-fill-mode: forwards;
	}

	@keyframes mymoveout {
		from {
			height: 92rpx;
		}

		to {
			height: 0;
		}
	}

	.zIndexDown {
		animation: opacity 0.3s 1;
		animation-fill-mode: forwards;
	}

	@keyframes opacity {
		from {
			opacity: 1;
		}

		to {
			opacity: 0;
		}
	}

	.zIndexUp {
		animation: opacityBack 0.3s 1;
		animation-fill-mode: forwards;
	}

	@keyframes opacityBack {
		from {
			opacity: 0;
		}

		to {
			opacity: 1;
		}
	}

	.tabBtnList {
		button {
			width: 260rpx !important;
		}

	}

	.tabBtnList {
		padding: 60rpx 24rpx 0;
		display: flex;
		flex-wrap: wrap;

		.weui-cells {
			width: 32.12%;
			margin: 10rpx 0.6% 0;
		}
	}

	.cmsBannerBox {
		margin-top: 30rpx;
	}

	.relative {
		position: relative;
	}

	.track-style {
		position: absolute;
		width: 46%;
		height: 45%;
		background: red;
		right: 4%;
		bottom: 0;
	}

	.item_content .text {
		font-size: 20rpx;
	}

	.paty-payment {
		width: calc(100% - 52rpx);
		height: 90rpx;
		margin: 0 auto;
		position: fixed;
		left: 0;
		right: 0;
		top: 10.5%;
		border-radius: 8rpx;
		background-color: #4D4D4D;
		color: #fff;
		display: flex;
		align-items: center;
		padding: 0 30rpx;
		z-index: 99;
		justify-content: space-between;

		text {
			font-size: 28rpx;
		}

		image {
			width: 28rpx;
		}
	}

	.viplist-title-text {
		font-size: 36rpx;
		font-weight: 500;
		color: #000;
		height: 116rpx;
		line-height: 116rpx;
		font-family: "NotoSansSC-Medium";
	}

	.online-box {
		display: none;
	}

	.animation-container {
		img {
			height: 0 !important;
		}
	}





	/*会员专区动画*/
	.animate-drop-down {
		animation: slideDown 0.4s ease-out forwards;
	}

	@keyframes slideDown {
		0% {
			transform: translateY(0);
			opacity: 1;
		}

		100% {
			transform: translateY(176rpx);
			opacity: 1;
		}
	}

	.animate-drop-up {
		animation: slideUp 0.4s ease-out forwards;
	}

	@keyframes slideUp {
		0% {
			transform: translateY(176rpx);
			opacity: 1;
		}

		100% {
			transform: translateY(0);
			opacity: 1;
		}
	}
</style>
